<template>
    <div class="form-wrapper">
        <el-form label-width="80px" style="margin-top: 20px;margin-left: -32px;" :model="dataForm" ref="dataFormRef" :rules="rules">
            <el-form-item>
                <h3 style="margin-right: 20px;">新增属性显示配置</h3>
                <el-button style="background: rgba(22, 119, 255, 1);color: #fff;border-radius: 5px;"
                    @click="addOrUpdateHandle()">选择属性组</el-button>
            </el-form-item>
            <el-form-item v-show="dataForm.groupName">
                <div>
                    <div class="group-title">
                        <span>{{ dataForm.groupName }}</span>
                        <el-form-item prop="sort">
                            <span>排序</span>
                            <el-input placeholder="请输入" v-model="dataForm.sort"  style="width: 300px;"></el-input>
                        </el-form-item>
                    </div>
                    <div v-for ="(item,index) in dataForm.attrConfigList">
                        <div class="group-title2">
                          <span>{{ item.attrName }}</span>
                          <el-switch v-model="item.switchFlag" class="ml-2" @change="switchChange(item)"
                                     style="--el-switch-on-color: #409EFF; --el-switch-off-color: #A8ABAE" />
                        </div>
                         <div class="group-main" v-show="item.switchFlag">
                        <div>
                          <span>属性选择方式</span>
                          <el-radio-group v-model="item.type">
                            <el-radio label="0">单选</el-radio>
                            <el-radio label="1" v-show="item.valueType != 1">多选</el-radio>
                          </el-radio-group>
                        </div>
                        <div style="margin-top: 20px;">
                          <span>属性显示方式</span>
                          <el-radio-group v-model="item.valueType">
                            <el-radio label="0">选项</el-radio>
                            <el-radio label="1" v-show="item.type != 1">范围</el-radio>
                          </el-radio-group>
                        </div>
                        <!-- 选项显示内容 -->
                        <div v-if="item.valueType == 0" class="option-content">
                          <el-checkbox v-model="item.isAllSelected" :indeterminate="item.isIndeterminate" @change="allSelectChange(item)">全选</el-checkbox>
                          <div class="option-list">
                            <el-checkbox-group v-model="item.checkedValues">
                              <el-checkbox v-for="(option, index) in item.attrValueConfigList" :key="index" :label="option.attrValue">{{ option.attrValue }}</el-checkbox>
                            </el-checkbox-group>
                          </div>
                        </div>
                        <!-- 范围显示内容 -->
                        <div v-else class="range-content" >
                          <!-- 以下 -->
                          <el-form-item>
                            <el-input v-model="item.under" placeholder="请输入" type="number"
                                      style="width: 300px;margin-right: 10px;margin-bottom: 10px;"
                                      @blur="validateRange(item)"></el-input>
                            <el-text>以下</el-text>
                          </el-form-item>
                          <!-- 区间 -->
                          <el-form-item>
                            <div v-for="(range, index) in item.ranges" :key="index" class="model-item">
                              <el-input v-model="range.start" placeholder="请输入" type="number"
                                        style="width: 130px;margin-right: 10px;"
                                        @blur="validateRange(item)"></el-input>
                              <div style="margin-top: -10px;margin-left: -4px;">---</div>
                              <el-input v-model="range.end" placeholder="请输入" type="number"
                                        style="width: 130px;margin-left: 10px;"
                                        @blur="validateRange(item)"></el-input>
                              <el-text></el-text>
                              <img src="../../assets/images/add.jpg" alt="" @click="addRangeModel(item)"
                                   class="addmodel">
                              <img v-if="item.ranges?.length > 1" src="../../assets/images/delete2.jpg" alt=""
                                   @click="removeRangeModel(item, index)">
                            </div>
                          </el-form-item>

                          <!-- 以上 -->
                          <el-form-item>
                            <el-input v-model="item.above" placeholder="请输入" type="number"
                                      style="width: 300px;"
                                      @blur="validateRange(item)"></el-input>
                            <el-text>以上</el-text>
                          </el-form-item>
                        </div>
                      </div>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <div class="button-container">
            <el-button @click="cancel" class="quxiao">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
        </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="getAttrGroup"></add-or-update>
</template>

<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { nextTick, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from 'vue-router';
import useView from "@/hooks/useView";
import AddOrUpdate from "./attribute-list-group-single.vue";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const dataFormRef = ref();

// 统一使用dataForm管理表单数据
const dataForm = reactive({
    id: "",
    groupId:"",
    groupName:"",
    sort: "", // 排序输入框的值
    attrConfigList:[] as AttrConfig[]
});

const isSubmitting = ref(false);

const rules = reactive({
  sort: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!/^[1-9]\d*$/.test(value)) {
          callback(new Error("请输入大于0的整数"));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

interface AttrConfig {
  id?: number;
  groupConfigId: number;
  attrId: number;
  type: number;
  valueType: number;
  attrName: string;
  switchFlag: boolean;
  isAllSelected: boolean;
  isIndeterminate: boolean;
  checkedValues: string[];
  attrValueConfigList: ValueConfig[];
  under?: { id?: number; attrConfigId?: number, attrValue: string}; // 以下区间
  above?: { id?: number; attrConfigId?: number, attrValue: string}; // 以上区间
  ranges?: { id?: number; attrConfigId?: number, start: string; end: string }[];
}

interface ValueConfig {
  id?: number;
  attrConfigId?: number;
  attrId: number;
  valueType: number;
  attrValue: string;
  chooseFlag?: boolean;

}
const route = useRoute();
const router = useRouter();
const id = route.query.id;
const switchChange = (item: AttrConfig) => {
  console.log(dataForm.attrConfigList)
  console.log(item.switchFlag)
  console.log(item)
};
const init = () => {

  console.log(dataFormRef.value);

  // 重置表单数据
  if (dataFormRef.value) {
    console.log(11111111111);
    dataFormRef.value.resetFields();
  }
  dataForm.id = '';
  dataForm.groupId = '';
  dataForm.groupName = '';
  dataForm.sort = '';
  dataForm.attrConfigList = [];
  // 如果是编辑模式，则获取属性组配置信息
  if (id) {
    dataForm.id = id.toString();
    baseService.get(`/noc/attrgroupconfig/info/${id}`).then(async res => {
      if (res.code == 0 && res.data) {
        dataForm.id = res.data.id;
        dataForm.groupId = res.data.groupId;
        dataForm.groupName = res.data.groupName;
        dataForm.sort = res.data.sort;
        dataForm.attrConfigList = res.data.attrConfigList;
        // 重新组装 attrConfigList，兼容区间型和选项型
        dataForm.attrConfigList = (res.data.attrConfigList || []).map((item: any) => {
          item.under = { attrValue: '' };
          item.above = { attrValue: '' };
          item.ranges = [{ start: '', end: '' }];
          item.type = item.type + '';
          item.valueType = item.valueType + '';

          // 区间型
          if (item.valueType == '1') {
            // 兼容后端返回 attrValueConfigList，按 valueType 分类赋值
            const underObj = (item.attrValueConfigList || []).find((v: any) => v.valueType === 1);
            console.log(item.under)
            //item.under =  {id: underObj.id, attrConfigId: underObj.attrConfigId, attrValue: underObj.attrValue};
            item.under = underObj.attrValue;
            console.log("under");
            console.log(item.under)
            const aboveObj = (item.attrValueConfigList || []).find((v: any) => v.valueType === 3);
            console.log(item.above)
            //item.above = {id: aboveObj.id, attrConfigId: aboveObj.attrConfigId, attrValue: aboveObj.attrValue};
            item.above = aboveObj.attrValue;
            console.log("above");
            console.log(item.above)
            // valueType=2 的集合赋值到 ranges
            const rangeArr = (item.attrValueConfigList || []).filter((v: any) => v.valueType === 2);
            item.ranges = rangeArr.length > 0 ? rangeArr.map((r: ValueConfig) => {
              const [start, end] = (r.attrValue || '').split(',');
              return {
                id: r.id,
                attrConfigId: r.attrConfigId,
                start: start !== undefined ? start : '',
                end: end !== undefined ? end : ''
              };
            }) : [{ start: '', end: '' }];
          }
          // 新增逻辑：处理全选状态
          if (item.valueType == '0') { // 仅处理选项型
            const allChooseFlag = item.attrValueConfigList.every((opt: ValueConfig) => opt.chooseFlag === true);
            if (allChooseFlag) {
              item.isAllSelected = true;
              item.checkedValues = item.attrValueConfigList.map((opt: ValueConfig) => opt.attrValue);
            } else {
              item.isAllSelected = false;
              item.checkedValues = item.attrValueConfigList
                .filter((opt: ValueConfig) => opt.chooseFlag)
                .map((opt: ValueConfig) => opt.attrValue);
            }
            // 计算 indeterminate 状态
            const checkedCount = item.attrValueConfigList.filter(opt => opt.chooseFlag).length;
            item.isIndeterminate = checkedCount > 0 && checkedCount < item.attrValueConfigList.length;
          }
          console.log('--------------')
          console.log(item)
          return item;
        });

        // 异步获取所有需要更新的属性值配置
        const updatePromises = dataForm.attrConfigList.map(async (item: any) => {
          if (item.valueType == '1') { // 区间型需要重新获取数据
            try {
              item.attrValueConfigList = await getValueConfigList(item.attrId);
              console.log('异步获取的属性值配置:', item.attrValueConfigList);
            } catch (error) {
              console.error('获取属性值配置失败:', error);
              item.attrValueConfigList = []; // 设置默认值
            }
          }
          return item;
        });

        // 等待所有异步操作完成
        await Promise.all(updatePromises);

        console.log(1111111111111111111111111111111111111111111)
        console.log( dataForm.attrConfigList)
        initCheckedValuesForAll();
      } else {
        ElMessage.error('获取属性组配置信息失败');
      }
    });
  }
};
const getValueConfigList = (attrId: number) => {
  // 返回 Promise，异步获取属性值配置列表
  return baseService.get(`/noc/attrvalueconfig/getAttrValueConfigList`, {attrId: attrId}).then(res => {
    if (res.code == 0 && res.data) {
      let valueConfigList = res.data?.map((str: string) => ({
        attrId: attrId,
        valueType: 0,
        attrValue: str,
        chooseFlag: false
      }))
      return valueConfigList;
    } else {
      ElMessage.error('获取属性值失败');
      return [];
    }
  });
};

const getAttrGroup = async (attrGroupData: any) => {
  if (!attrGroupData[0]) {
    return;
  }
  let attrGroup = attrGroupData[0];
  dataForm.groupId = attrGroup.id;
  dataForm.groupName = attrGroup.groupName;
  // 使用 Promise.all 并行获取所有属性的值配置
  const attrConfigList = await Promise.all(attrGroup.attrClassifyList.map(async (item: any) => {
    const valueConfigList = await getValueConfigList(item.id);
    return {
      attrId: item.id,
      attrName: item.className,
      switchFlag: false,
      isAllSelected: false,
      isIndeterminate: false,
      attrValueConfigList: valueConfigList,
      ranges: [{ id:'', attrConfigId: '', start: '', end: '' }], // 初始化区间
    };
  }));
  dataForm.attrConfigList = attrConfigList;
  initCheckedValuesForAll(); // 只在此处调用一次
  console.log(dataForm.attrConfigList);
};
init();

// 添加区间价格输入框（针对每个属性项）
const addRangeModel = (item: AttrConfig) => {
  if (!Array.isArray(item.ranges)) {
    item.ranges = [{ start: '', end: '' }]; // 类型安全初始化
  }
  (item.ranges as { start: string; end: string }[]).push({ start: '', end: '' }); // 类型断言
};

// 删除区间价格输入框（针对每个属性项）
const removeRangeModel = (item: AttrConfig, index: number) => {
  if (!Array.isArray(item.ranges)) {
    item.ranges = [{ start: '', end: '' }];
  }
  if (item.ranges.length <= 1) {
    ElMessage.warning('至少需要一个价格区间');
    return;
  }
  (item.ranges as { start: string; end: string }[]).splice(index, 1);
};

// 选择属性组
const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
    addKey.value++;
    nextTick(() => {
        addOrUpdateRef.value.init(id);
    });
};
const view = reactive({});
const state = reactive({ ...useView(view) });
const cancel = () => {
  router.push('/program/attribute-list');
  // 关闭当前标签页（需确保useView hook已正确配置）
  state.closeCurrentTab();
};
// 表单提交
const dataFormSubmitHandle = () => {
  // if (isSubmitting.value) {
  //       return;
  //   }
  //   isSubmitting.value = true;
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
      // isSubmitting.value = false;
    }
    // 仅保留 switchFlag 为 true 的属性项
    const filteredAttrConfigList = dataForm.attrConfigList.filter((item: any) => item.switchFlag);
    if (!filteredAttrConfigList.length) {
      ElMessage.warning("请至少开启一个属性项！");
      return false;
    }
    // 整理参数对象
    const params: any = {};
    params.id = dataForm.id;
    params.groupId = dataForm.groupId;
    params.groupName = dataForm.groupName;
    params.sort = dataForm.sort;
    // 每个属性项下挂载 attrValueConfigList
    params.attrConfigList = filteredAttrConfigList.map((item: any) => {
      const attrValueConfigList: any[] = [];
      if (item.type == null || item.type == undefined) {
        ElMessage.warning("属性选择方式不可为空！");
        return false;
      }
      if (item.valueType == null || item.valueType == undefined) {
        ElMessage.warning("属性显示方式不可为空！");
        return false;
      }
      // 选项型
      if (item.valueType == 0) {
        console.log(1111111111);
        console.log(item.attrValueConfigList);
        console.log(item.checkedValues);
        console.log(item.chooseFlag);
        if (Array.isArray(item.checkedValues)) {
          console.log(33333333);
          item.checkedValues.forEach((val: any) => {
            const matchedOption = item.attrValueConfigList.find((opt: ValueConfig) => opt.attrValue == val);
            attrValueConfigList.push({
              id: matchedOption ? matchedOption.id : '',
              attrConfigId: matchedOption ? matchedOption.attrConfigId : '',
              attrId: item.attrId,
              valueType: 0,
              attrValue: val
            });
          });
        }
        console.log(attrValueConfigList);
      }
      // 区间型
      if (item.valueType == 1) {
        
        // 以下区间
        if (item.under !== undefined && item.under !== "") {

          attrValueConfigList.push({
            id: item.under.id || '',
            attrConfigId: item.under.attrConfigId || '',
            attrId: item.attrId,
            valueType: 1,
            attrValue: item.under
          });
        }
        // 区间段
        if (Array.isArray(item.ranges)) {

          item.ranges.forEach((range: any, index: number) => {
            if (range.start !== undefined && range.end !== undefined && range.start !== "" && range.end !== "") {
              attrValueConfigList.push({
                id: range.id || '', // 修正为 range.id
                attrConfigId: range.attrConfigId || '', // 修正为 range.attrConfigId
                attrId: item.attrId,
                valueType: 2,
                attrValue: range.start + "," + range.end,
                sort: index
              });
            }
          });
        }
        // 以上区间
        if (item.above !== undefined && item.above !== "") {

          attrValueConfigList.push({
            id: item.above.id || '',
            attrConfigId: item.above.attrConfigId || '' ,
            attrId: item.attrId,
            valueType: 3,
            attrValue: item.above
          });
        }
      }
      return {
        id: item.id,
        groupConfigId: item.groupConfigId,
        attrId: item.attrId,
        type: item.type,
        valueType: item.valueType,
        attrValueConfigList
      };
    });
    console.log(params.attrConfigList);
    // 若某属性项无有效值也提示
    const emptyValueItem = params.attrConfigList.find((item: any) => !item.attrValueConfigList.length);
    if (emptyValueItem) {
      ElMessage.warning("存在属性项未填写有效值，请检查！");
      return false;
    }
    // 提交
    const url = !dataForm.id ? "/noc/attrgroupconfig/save" : "/noc/attrgroupconfig/update";
    baseService[!dataForm.id ? 'post' : 'put'](url, params).then((res: any) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          // 关闭当前标签页（需确保useView hook已正确配置）
          state.closeCurrentTab();
          router.push({
          path: '/program/attribute-list',
          query: { activeTab: 'tableTab' }
        }).then(() => {
          router.go(0);
        });
        }
      });
    });
  });
};

// 全选/反选事件
const allSelectChange = (item: AttrConfig) => {
  if (item.isAllSelected) {
    item.checkedValues = item.attrValueConfigList.map(opt => opt.attrValue);
  } else {
    item.checkedValues = [];
  }
};

// 在 getAttrGroup、init 等数据初始化后调用
function initCheckedValuesForAll() {
  dataForm.attrConfigList.forEach(item => {
    // 判空保护，防止 attrValueConfigList 为 undefined
    if (!Array.isArray(item.attrValueConfigList)) {
      item.attrValueConfigList = [];
    }
    if (item.valueType == 0) {
      item.checkedValues = item.attrValueConfigList.filter(opt => opt.chooseFlag).map(opt => opt.attrValue);
      watch(() => item.checkedValues, (newVal) => {
        item.attrValueConfigList.forEach(opt => {
          opt.chooseFlag = newVal.includes(opt.attrValue);
        });
        // 更新 isAllSelected 和 isIndeterminate
        const checkedCount = item.attrValueConfigList.filter(opt => opt.chooseFlag).length;
        const totalCount = item.attrValueConfigList.length;
        if (checkedCount == totalCount && totalCount > 0) {
          item.isAllSelected = true;
          item.isIndeterminate = false;
        } else if (checkedCount > 0 && checkedCount < totalCount) {
          item.isAllSelected = false;
          item.isIndeterminate = true;
        } else {
          item.isAllSelected = false;
          item.isIndeterminate = false;
        }
      }, { deep: true });
    }
  });
}
// 校验区间输入规则（放在 <script setup> 内）
// function validateRange(item: AttrConfig) {
//   // 2. 区间中第一条的start值不能小于under值
//   if (item.ranges.length > 0 && item.under !== undefined && item.under !== '' && item.ranges[0].start !== undefined && item.ranges[0].start !== '') {
//     if (Number(item.ranges[0].start) < Number(item.under)) {
//       ElMessage.warning('区间第一条的起始值不能小于“以下”值');
//       return;
//     }
//   }
//   // 3. 区间中，下一条的start值不能小于上一条的end
//   for (let i = 1; i < item.ranges.length; i++) {
//     if (item.ranges[i].start !== undefined && item.ranges[i].start !== '' && item.ranges[i-1].end !== undefined && item.ranges[i-1].end !== '') {
//       if (Number(item.ranges[i].start) < Number(item.ranges[i-1].end)) {
//         ElMessage.warning('后一条区间的起始值不能小于前一条的结束值');
//         return;
//       }
//     }
//   }
//   // 4. 区间中最后一条的end值不能小于above值
//   if (item.ranges.length > 0 && item.above !== undefined && item.above !== '' && item.ranges[item.ranges.length-1].end !== undefined && item.ranges[item.ranges.length-1].end !== '') {
//     if (Number(item.ranges[item.ranges.length-1].end) < Number(item.above)) {
//       ElMessage.warning('区间最后一条的结束值不能小于“以上”值');
//       return;
//     }
//   }
//   // 5. 如果没有区间值，above值不能小于under
//   if ((!item.ranges || item.ranges.length === 0) && item.above !== undefined && item.above !== '' && item.under !== undefined && item.under !== '') {
//     if (Number(item.above) < Number(item.under)) {
//       ElMessage.warning('“以上”值不能小于“以下”值');
//       return;
//     }
//   }
//   // 6. 区间值不能只填写start或者只填写end
//   for (let i = 0; i < item.ranges.length; i++) {
//     const range = item.ranges[i];
//     if ((range.start !== '' && range.end === '') || (range.start === '' && range.end !== '')) {
//       ElMessage.warning('区间必须同时填写起始值和结束值');
//       return;
//     }
//   }
// }
</script>

<style lang="scss" scoped>
.form-wrapper {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 10px;
    margin-top: 20px;
}

.group-title {
    width: 690px;
    height: 61px;
    line-height: 61px;
    border: 1px solid rgba(199, 199, 199, 1);
    display: flex;
    justify-content: space-between;
    padding: 0px 20px 0px 20px;
}

.group-title span {
    font-size: 14px;
    margin-right: 10px;
}

.el-input {
    width: 224px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
}

.group-title2 {
    width: 690px;
    height: 50px;
    line-height: 50px;
    border-top: none;
    border-left: 1px solid rgba(199, 199, 199, 1);
    border-right: 1px solid rgba(199, 199, 199, 1);
    border-bottom: 1px solid rgba(199, 199, 199, 1);
    display: flex;
    justify-content: space-between;
    padding: 0px 20px 0px 20px;
}

.el-switch {
    margin-top: 1dvh;
}

.group-main {
    width: 690px;
    height: auto;
    border-top: none;
    border-left: 1px solid rgba(199, 199, 199, 1);
    border-right: 1px solid rgba(199, 199, 199, 1);
    border-bottom: 1px solid rgba(199, 199, 199, 1);
    padding: 20px 20px 20px 20px;
}

.group-main span {
    font-size: 14px;
    margin-right: 40px;
}

.option-content,
.range-content {
    margin-top: 15px;
    border-radius: 4px;
}

.option-list {
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin-top: 10px;
}

.range-item {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 10px;
}

.model-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.model-select {
    padding: 8px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.model-input {
    padding: 8px;
    margin-right: 10px;
    border-radius: 5px;
    width: 218px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(199, 199, 199, 1);
}

.el-text {
    color: #606266;
    margin-left: 30px;
}

.addmodel {
    margin-left: 10px;
    margin-right: 20px;
}

.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
    margin-right: 10px;
}
</style>
